package com.guoxin.part1.chapter5;

import java.util.LinkedList;

/**
 * 线程间通信
 *
 * @author guoxin
 * @date 2019/8/28
 */
public class EventQueue<T> {
    private final int capacity;
    private static final int DEFAULT_MAX_EVENT = 10;
    private final LinkedList<T> eventQueue = new LinkedList<>();

    public EventQueue(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("capacity can't less than or equal to zero");
        }
        this.capacity = capacity;
    }

    public EventQueue() {
        this(DEFAULT_MAX_EVENT);
    }

    public void offer(T t) {
        synchronized (eventQueue) {
            while (eventQueue.size() >= capacity) {
                try {
                    console("the queue is full.");
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            eventQueue.addLast(t);
            eventQueue.notifyAll();
            console("the new event is submitted");
        }
    }


    public T take() {
        synchronized (eventQueue) {
            while (eventQueue.isEmpty()) {
                try {
                    console("the queue is empty.");
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = eventQueue.removeFirst();
            eventQueue.notifyAll();
            console("the event " + t + " is handled.");
            return t;
        }
    }

    private void console(String message) {
        System.out.printf("%s:%s queue size is " + eventQueue.size() + "\n", Thread.currentThread().getName(), message);
    }
}
